<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>8-1鼠标事件</title>
</head>
<body>
<div id="c"></div>

<script src="../js/matter.js"></script>
<script>
  let Engine = Matter.Engine // 引擎.引擎模块包含创建和操作引擎的方法
  let Render = Matter.Render // 基于HTML5画布的渲染器
  let Bodies = Matter.Bodies // 用于创建各种形状的物体，物体必须添加到Wolrd中，然后由引擎运行世界
  let Composite = Matter.Composite // 复合体，旧版的 Matter.World 已经合并到这个模块里
  let Runner = Matter.Runner // 循环模块
  let Mouse = Matter.Mouse
  let MouseConstraint = Matter.MouseConstraint
  let Events = Matter.Events

  // 创建引擎
  let engine = Engine.create()

  // 创建渲染器
  let render = Render.create({
    element: document.getElementById('c'), // 绑定页面元素,
    engine: engine,
    options: {
      width: 400,
      height: 400,
      wireframes: false, // 关闭线框模式
      showVelocity: true // 显示速度
    }
  })

  // 矩形 x, y, width, height
  let rect = Bodies.rectangle(200, 200, 80, 80)

  // 地面
  let ground = Bodies.rectangle(200, 390, 400, 20, {
    isStatic: true,
    render: {
      fillStyle: '#cccccc'
    }
  })

  // 创建一个 Mouse 实例
  let mouse = Mouse.create(render.canvas)

  let mouseConstraint = MouseConstraint.create(engine, {
    mouse: mouse
  })

  Composite.add(engine.world, [rect, ground, mouseConstraint])

  // 监听鼠标按下事件
  Events.on(mouseConstraint, 'mousedown', function(event) {
    console.log('按下')
  })

  // 监听鼠标移动事件
  Events.on(mouseConstraint, "mousemove", function(event) {
    console.log('移动')
  })

  // 监听鼠标抬起事件
  Events.on(mouseConstraint, "mouseup", function(event) {
    console.log('抬起')
  })

  // 监听鼠标拖拽刚体 - 开始拖拽
  Events.on(mouseConstraint, 'startdrag', function(event) {
    console.log('开始拖拽')
  })

  // 监听鼠标拖拽刚体 - 结束拖拽
  Events.on(mouseConstraint, 'enddrag', function(event) {
    console.log('结束拖拽')
  })

  Render.run(render)

  // 创建运行方法
  let runner = Runner.create()

  // 运行渲染器
  Runner.run(runner, engine)
</script>
</body>
</html>